package com.sh.d1.gameserver.cmdhandler;

import com.sh.d1.gameserver.msg.GameMsgProtocol;
import com.sh.d1.gameserver.rank.RankItem;
import com.sh.d1.gameserver.rank.RankService;

import java.util.Collections;

/**
 * 获取排行榜指令处理器
 */
public class GetRankCmdHandler implements ICmdHandler<GameMsgProtocol.GetRankCmd> {
    @Override
    public void handle(MyCmdHandlerContext ctx, GameMsgProtocol.GetRankCmd cmd) {
        if (null == ctx ||
            null == cmd) {
            return;
        }

        RankService.getInstance().getRank((rankItemList) -> {
            if (null == rankItemList) {
                rankItemList = Collections.emptyList();
            }

            GameMsgProtocol.GetRankResult.Builder
                resultBuilder = GameMsgProtocol.GetRankResult.newBuilder();

            for (RankItem currItem : rankItemList) {
                if (null == currItem) {
                    continue;
                }

                // 创建排名条目
                GameMsgProtocol.GetRankResult.RankItem.Builder
                    currItemBuilder = GameMsgProtocol.GetRankResult.RankItem.newBuilder();

                currItemBuilder.setRankId(currItem.rankId);
                currItemBuilder.setUserId(currItem.userId);
                currItemBuilder.setUserName(currItem.userName);
                currItemBuilder.setHeroAvatar(currItem.heroAvatar);
                currItemBuilder.setWin(currItem.win);

                resultBuilder.addRankItem(currItemBuilder);
            }

            // 构建结果并发布
            GameMsgProtocol.GetRankResult newResult = resultBuilder.build();
            ctx.writeAndFlush(newResult);

            return null;
        });
    }
}
